import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../routes/routes.dart';
import 'package:intl/intl.dart';

class UserProfilePage extends StatefulWidget {
  final String userId;
  final String userNickname;
  final String userAvatarUrl;

  const UserProfilePage({
    Key? key,
    required this.userId,
    required this.userNickname,
    required this.userAvatarUrl,
  }) : super(key: key);

  @override
  _UserProfilePageState createState() => _UserProfilePageState();
}

class _UserProfilePageState extends State<UserProfilePage> with SingleTickerProviderStateMixin {
  bool _isFollowing = false;
  final int _postsCount = 42; // 模拟数据
  final int _followingCount = 168; // 模拟数据
  final int _followersCount = 320; // 模拟数据
  final int _likesCount = 1580; // 模拟数据
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 自定义AppBar，带有渐变背景
          SliverAppBar(
            expandedHeight: 180.0,
            floating: false,
            pinned: true,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back, color: Colors.white),
              onPressed: () => Get.back(),
            ),
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                widget.userNickname,
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                ),
              ),
              background: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [Color(0xFF3F51B5), Color(0xFF7986CB)],
                  ),
                ),
                child: Stack(
                  children: [
                    // 背景装饰图案
                    Positioned(
                      right: -30,
                      top: -30,
                      child: Container(
                        width: 150,
                        height: 150,
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.1),
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                    Positioned(
                      left: -20,
                      bottom: -20,
                      child: Container(
                        width: 100,
                        height: 100,
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.1),
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            actions: [
              IconButton(
                icon: const Icon(Icons.message_outlined, color: Colors.white),
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('聊天功能开发中')),
                  );
                },
              ),
              IconButton(
                icon: const Icon(Icons.more_vert, color: Colors.white),
                onPressed: () {
                  _showOptionsMenu(context);
                },
              ),
            ],
          ),
          SliverToBoxAdapter(
            child: Column(
              children: [
                // 用户信息卡片
                _buildUserInfoCard(),
                
                // 标签栏
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.1),
                        spreadRadius: 1,
                        blurRadius: 3,
                        offset: const Offset(0, 1),
                      ),
                    ],
                  ),
                  child: TabBar(
                    controller: _tabController,
                    labelColor: const Color(0xFF3F51B5),
                    unselectedLabelColor: Colors.grey[600],
                    indicatorColor: const Color(0xFF3F51B5),
                    indicatorSize: TabBarIndicatorSize.label,
                    tabs: const [
                      Tab(text: "动态"),
                      Tab(text: "相册"),
                      Tab(text: "喜欢"),
                    ],
                  ),
                ),
                
                // 标签页内容
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.6,
                  child: TabBarView(
                    controller: _tabController,
                    children: [
                      _buildPostsList(),
                      _buildPhotosGrid(),
                      _buildLikedContent(),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 用户信息卡片
  Widget _buildUserInfoCard() {
    return Card(
      margin: const EdgeInsets.all(16.0),
      elevation: 2.0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16.0),
      ),
      child: Column(
        children: [
          // 用户基本信息
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户头像
                Container(
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: const Color(0xFF3F51B5), width: 2),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: CircleAvatar(
                    radius: 40,
                    backgroundImage: NetworkImage(widget.userAvatarUrl),
                  ),
                ),
                const SizedBox(width: 16.0),
                
                // 用户信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 用户昵称和性别图标
                      Row(
                        children: [
                          Text(
                            widget.userNickname,
                            style: const TextStyle(
                              fontSize: 22,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF333333),
                            ),
                          ),
                          const SizedBox(width: 8),
                          // 性别图标（示例）
                          Container(
                            padding: const EdgeInsets.all(4),
                            decoration: BoxDecoration(
                              color: Colors.blue[100],
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: const Icon(
                              Icons.male,
                              color: Colors.blue,
                              size: 16,
                            ),
                          ),
                          const Spacer(),
                          // 关注状态标签
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: _isFollowing ? Colors.grey[200] : Colors.blue[50],
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Text(
                              _isFollowing ? '已关注' : '未关注',
                              style: TextStyle(
                                color: _isFollowing ? Colors.black54 : const Color(0xFF3F51B5),
                                fontSize: 12,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4.0),
                      
                      // 用户ID
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                        decoration: BoxDecoration(
                          color: const Color(0xFFE8EAF6),
                          borderRadius: BorderRadius.circular(12.0),
                        ),
                        child: Text(
                          'ID: ${widget.userId}',
                          style: const TextStyle(
                            color: Color(0xFF3F51B5),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      
                      // 个人签名
                      const SizedBox(height: 8.0),
                      const Text(
                        '这是用户的个人签名，展示个性和风格~',
                        style: TextStyle(
                          color: Color(0xFF666666),
                          fontSize: 14,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          
          // 统计数据
          Container(
            padding: const EdgeInsets.symmetric(vertical: 12.0),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: const BorderRadius.only(
                bottomLeft: Radius.circular(16.0),
                bottomRight: Radius.circular(16.0),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem('帖子', _postsCount.toString()),
                _buildDivider(),
                _buildStatItem('关注', _followingCount.toString()),
                _buildDivider(),
                _buildStatItem('粉丝', _followersCount.toString()),
                _buildDivider(),
                _buildStatItem('获赞', _likesCount.toString()),
              ],
            ),
          ),
          
          // 操作按钮
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                // 关注按钮
                Expanded(
                  flex: 3,
                  child: ElevatedButton(
                    onPressed: () {
                      setState(() {
                        _isFollowing = !_isFollowing;
                      });
                      // 显示提示
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text(_isFollowing ? '已关注 ${widget.userNickname}' : '已取消关注 ${widget.userNickname}'),
                          duration: const Duration(seconds: 1),
                        ),
                      );
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _isFollowing ? Colors.grey[300] : const Color(0xFF3F51B5),
                      foregroundColor: _isFollowing ? Colors.black87 : Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    child: Text(_isFollowing ? '已关注' : '关注', style: const TextStyle(fontSize: 16)),
                  ),
                ),
                const SizedBox(width: 12),
                // 发消息按钮
                Expanded(
                  flex: 2,
                  child: OutlinedButton.icon(
                    icon: const Icon(Icons.message_outlined, size: 18),
                    label: const Text('发消息'),
                    onPressed: () {
                      // 跳转到聊天页面
                      Get.toNamed(
                        Routes.CHAT,
                        arguments: {
                          'userId': widget.userId,
                          'userNickname': widget.userNickname,
                          'userAvatarUrl': widget.userAvatarUrl,
                        },
                      );
                    },
                    style: OutlinedButton.styleFrom(
                      foregroundColor: const Color(0xFF3F51B5),
                      side: const BorderSide(color: Color(0xFF3F51B5)),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 统计项
  Widget _buildStatItem(String label, String value) {
    return InkWell(
      onTap: () {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('查看$label详情功能开发中')),
        );
      },
      child: Column(
        children: [
          Text(
            value,
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Color(0xFF3F51B5),
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  // 分隔线
  Widget _buildDivider() {
    return Container(
      height: 30,
      width: 1,
      color: Colors.grey[300],
    );
  }

  // 帖子列表
  Widget _buildPostsList() {
    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemCount: 5, // 显示5个帖子
      itemBuilder: (context, index) {
        return Card(
          margin: const EdgeInsets.only(bottom: 16.0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.0),
          ),
          elevation: 1.0,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 帖子头部
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: Row(
                  children: [
                    CircleAvatar(
                      radius: 20,
                      backgroundImage: NetworkImage(widget.userAvatarUrl),
                    ),
                    const SizedBox(width: 12),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.userNickname,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                        ),
                        Text(
                          '${DateTime.now().subtract(Duration(days: index)).day}天前',
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                    const Spacer(),
                    IconButton(
                      icon: const Icon(Icons.more_horiz),
                      onPressed: () {},
                    ),
                  ],
                ),
              ),
              
              // 帖子内容
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 12.0),
                child: Text(
                  '这是第${index + 1}条动态内容，分享生活点滴和有趣的事情。#生活记录 #日常分享',
                  style: const TextStyle(fontSize: 15),
                ),
              ),
              
              // 帖子图片
              Container(
                height: 200,
                margin: const EdgeInsets.symmetric(vertical: 12.0),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: NetworkImage('https://picsum.photos/seed/${widget.userId}_$index/500/300'),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              
              // 帖子底部操作栏
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildPostAction(Icons.favorite_border, '${120 + index * 10}'),
                    _buildPostAction(Icons.chat_bubble_outline, '${45 + index * 5}'),
                    _buildPostAction(Icons.share_outlined, '${12 + index}'),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 帖子操作按钮
  Widget _buildPostAction(IconData icon, String count) {
    return InkWell(
      onTap: () {},
      child: Row(
        children: [
          Icon(icon, size: 20, color: Colors.grey[700]),
          const SizedBox(width: 4),
          Text(
            count,
            style: TextStyle(
              color: Colors.grey[700],
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  // 相册网格
  Widget _buildPhotosGrid() {
    return GridView.builder(
      padding: const EdgeInsets.all(12.0),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: 1.0,
        crossAxisSpacing: 8.0,
        mainAxisSpacing: 8.0,
      ),
      itemCount: 15, // 显示15张照片
      itemBuilder: (context, index) {
        // 生成随机图片URL
        final imageUrl = 'https://picsum.photos/seed/${widget.userId}_photo_$index/300';
        
        return GestureDetector(
          onTap: () {
            // 点击照片的处理逻辑
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('照片查看功能开发中')),
            );
          },
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.0),
              image: DecorationImage(
                image: NetworkImage(imageUrl),
                fit: BoxFit.cover,
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 2,
                  offset: const Offset(0, 1),
                ),
              ],
            ),
            // 如果是视频，添加视频标识
            child: index % 5 == 0 ? const Align(
              alignment: Alignment.bottomRight,
              child: Padding(
                padding: EdgeInsets.all(4.0),
                child: Icon(
                  Icons.play_circle_outline,
                  color: Colors.white,
                  size: 24,
                ),
              ),
            ) : null,
          ),
        );
      },
    );
  }

  // 喜欢的内容
  Widget _buildLikedContent() {
    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemCount: 3, // 显示3个喜欢的内容
      itemBuilder: (context, index) {
        return Card(
          margin: const EdgeInsets.only(bottom: 16.0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.0),
          ),
          elevation: 1.0,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 内容头部
              ListTile(
                leading: CircleAvatar(
                  backgroundImage: NetworkImage('https://picsum.photos/seed/user_${100 + index}/100'),
                ),
                title: Text('用户${100 + index}'),
                subtitle: Text('${DateTime.now().subtract(Duration(days: index * 2)).day}天前'),
                trailing: IconButton(
                  icon: const Icon(Icons.favorite, color: Colors.red),
                  onPressed: () {},
                ),
              ),
              
              // 内容描述
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                child: Text(
                  '这是用户喜欢的第${index + 1}条内容，包含了有趣的信息和精彩的瞬间。',
                  style: const TextStyle(fontSize: 15),
                ),
              ),
              
              // 内容图片
              Container(
                height: 180,
                margin: const EdgeInsets.symmetric(vertical: 8.0),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: NetworkImage('https://picsum.photos/seed/liked_$index/500/300'),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              
              // 底部操作栏
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildPostAction(Icons.favorite, '${230 + index * 15}'),
                    _buildPostAction(Icons.chat_bubble_outline, '${78 + index * 7}'),
                    _buildPostAction(Icons.share_outlined, '${25 + index * 3}'),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 显示选项菜单
  void _showOptionsMenu(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16.0)),
      ),
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                margin: const EdgeInsets.symmetric(vertical: 8.0),
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2.0),
                ),
              ),
              ListTile(
                leading: const Icon(Icons.report_outlined, color: Colors.orange),
                title: const Text('举报用户'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('举报功能开发中')),
                  );
                },
              ),
              ListTile(
                leading: const Icon(Icons.block_outlined, color: Colors.red),
                title: const Text('屏蔽此人'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('屏蔽功能开发中')),
                  );
                },
              ),
              ListTile(
                leading: const Icon(Icons.share_outlined, color: Colors.blue),
                title: const Text('分享此主页'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('分享功能开发中')),
                  );
                },
              ),
              const SizedBox(height: 8),
            ],
          ),
        );
      },
    );
  }
}